package com.ruoyi.video.task;

import com.ruoyi.video.domain.VideoServer;
import com.ruoyi.video.server.AbstractServer;
import com.ruoyi.video.service.IVideoServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 服务相关的定时任务
 */
@Component
@Slf4j
public class ServerTask {

    @Autowired
    private IVideoServerService videoServerService;

    /**
     * 定时巡检各接入服务是否正常
     */
    @Scheduled(cron = "19 0/10 * * * ?")
    public void alive(){
        log.debug("定时巡检各接入服务是否正常");
        VideoServer vsc = new VideoServer();
        vsc.setStatus("1");
        List<VideoServer> list = videoServerService.selectVideoServerList(vsc);
        for(VideoServer videoServer:list){
            AbstractServer handler = ServerApplicationRunner.getHandler(videoServer.getCode());
            if(handler == null || handler.alive(videoServer)){
                continue;
            }

            //自动启动一次
            if(!handler.start(videoServer)) {
                log.error( "{} - {} 对接服务重启失败", "对接异常停止", videoServer.getCode(), videoServer.getName());

                videoServer.setRunning(VideoServer.STATE_STOP);
                videoServerService.updateVideoServer(videoServer);
            }
        }
    }

}
